//
//  EmoticonViewController.swift
//  EmKeyboard
//
//  Created by 崔洋洋 on 15/10/16.
//  Copyright © 2015年 崔洋洋. All rights reserved.
//

import UIKit

// Cell 的标示符
private let  YYEmoticonCellIdentifier = "YYEmoticonCellIdentifier"
// 表情键盘控制器
class EmoticonViewController: UIViewController {
    
    // MARK: 监听方法
    func clickItem(item: UIBarButtonItem) {
        print(item.tag)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: 搭建界面
    private func setupUI() {
        view.addSubview(collectionView)
        view.addSubview(toolbar)
        
        // 自动布局
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        let viewDict = ["cv": collectionView, "tb": toolbar]
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
        collectionView.backgroundColor = UIColor.whiteColor()
        // 准备控件
        prepareToolbar()
        prepareCollectionView()
        
    }
    
    // 准备集合视图 cv
    private func prepareCollectionView() {
        collectionView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: YYEmoticonCellIdentifier)
        collectionView.dataSource = self
    }
    
    // 准备工具栏
    private func prepareToolbar() {
        toolbar.tintColor = UIColor.darkGrayColor()
        var items = [UIBarButtonItem]()
        var index = 0
        for s in ["最近", "默认", "emoji", "浪小花"] {
            items.append(UIBarButtonItem(title: s, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            items.last?.tag = index++
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolbar.items = items
    }
    
    // MARK: 懒加载控件
    private lazy var packages = EmoticonPackage.packages()

    private lazy var toolbar = UIToolbar()
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: YYEmoticonLayout())
    
    // 表情键盘 - 私有类
    private class YYEmoticonLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            
            let w = collectionView!.bounds.width / 7.0
            let y = (collectionView!.bounds.height - 3 * w) * 0.499
            itemSize = CGSize(width: w, height: w)
            
            minimumInteritemSpacing  = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
            
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}


extension EmoticonViewController: UICollectionViewDataSource {
    // 分组数量 - 表情包数量
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    // 每个表情包中表情的数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YYEmoticonCellIdentifier, forIndexPath: indexPath) as! EmoticonCell
        
        cell.backgroundColor = (indexPath.item % 2 == 0) ? UIColor.orangeColor() : UIColor.greenColor()
        cell.emotion = packages[indexPath.section].emoticons![indexPath.item]
        return cell
    }
}

// 表情 Cell
private class EmoticonCell: UICollectionViewCell {
    
        
        // 表情
        var emotion: Emoticon? {
            didSet {
                // 按钮图像
                emoticonButton.setImage(UIImage(contentsOfFile: emotion!.imagePath), forState: UIControlState.Normal)
                // 设置 emoji
                emoticonButton.setTitle(emotion!.emoji, forState: UIControlState.Normal)
            }
        }
        override init(frame: CGRect) {
        super.init(frame: frame)
        
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        // 按钮字体
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        addSubview(emoticonButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: 懒加载控件
    private lazy var emoticonButton = UIButton()
}
